﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;

namespace MishraReader.Entities
{
    public sealed class FacebookShareService : ShareServiceBase
    {
        public const string AppID = "133409780084100";
        public const string AppSecret = "5c75247f8435e8c289cf99d5f2828bc4";

        public override bool IsSupported
        {
            get { return true; }
        }

        public FacebookShareService()
        {
            ServiceName = "Facebook";
            ServiceId = new Guid("7D2EA6A9-BE73-41BE-A496-6AEB49C2584F");
            ServiceType = ServiceType.Share;
        }

        public override void Share(ShareServiceAccount account, string message, Item item)
        {
            var webClient = new WebClient();

            var strRet = CreatePostString(account, null, item.Description, item.PostUri.ToString(), message, item.Title, item.ImageUrl);

            webClient.UploadString(new Uri("https://graph.facebook.com/me/feed", UriKind.Absolute), "POST", strRet);
        }

        private static string CreatePostString(ShareServiceAccount account, string caption, string description, string link, string message, string name,
                                               string pictureLink)
        {
            var strRet = "access_token=" + HttpUtility.UrlEncode(account.Token);
            if (!string.IsNullOrEmpty(caption))
            {
                strRet += "&caption=" + HttpUtility.UrlEncode(caption);
            }
            if (!string.IsNullOrEmpty(description))
            {
                strRet += "&description=" + HttpUtility.UrlEncode(description);
            }
            if (!string.IsNullOrEmpty(link))
            {
                strRet += "&link=" + HttpUtility.UrlEncode(link);
            }
            if (!string.IsNullOrEmpty(message))
            {
                strRet += "&message=" + HttpUtility.UrlEncode(message);
            }
            if (!string.IsNullOrEmpty(name))
            {
                strRet += "&name=" + HttpUtility.UrlEncode(name);
            }
            if (!string.IsNullOrEmpty(pictureLink))
            {
                strRet += "&picture=" + HttpUtility.UrlEncode(pictureLink);
            }
            return strRet;
        }
    }
}